// MIT License

// Copyright (c) 2021-2023 kadirlua

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "Client.h"
#include "network/SocketOption.h"

namespace sdk {
	namespace application {

		using namespace network;

		namespace {
			bool callbackInterrupt(void* userdata_ptr)
			{
				auto* client = static_cast<Client*>(userdata_ptr);
				return client->isInterrupted();
			}
		}

		Client::Client(const std::string& ip, int port,
			network::protocol_type type /*= protocol_type::tcp*/,
			network::IpVersion ipVer /*= IpVersion::IPv4*/) :
			m_socket{ std::make_unique<Socket>(port, type, ipVer) }
		{
			m_socket->setIpAddress(ip);
			m_socket->setInterruptCallback(&callbackInterrupt, this);
		}

		void Client::connectServer()
		{
			m_socket->connect();
			const SocketOption<Socket> socketOpt{ *m_socket };
			socketOpt.setBlockingMode(1);
			m_socket_obj = m_socket->createNewSocket(m_socket->getSocketId());
		}

		int Client::write(std::initializer_list<char> msg) const
		{
			return m_socket_obj->write(msg);
		}

		int Client::write(const char* msg, int msg_size) const
		{
			return m_socket_obj->write(msg, msg_size);
		}

		int Client::write(const std::string& msg) const
		{
			return m_socket_obj->write(msg);
		}

		int Client::write(const std::vector<unsigned char>& msg) const
		{
			return m_socket_obj->write(msg);
		}

		size_t Client::read(std::vector<unsigned char>& response_msg, int max_size /*= 0*/) const
		{
			return m_socket_obj->read(response_msg, max_size);
		}

		size_t Client::read(std::string& message, int max_size /*= 0*/) const
		{
			return m_socket_obj->read(message, max_size);
		}
	}
}